layui.use(['table', 'admin', 'ax','laydate','form','func','layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var form = layui.form;
    var $ax = layui.ax;
    var admin = layui.admin;
    var date = layui.laydate;
    var func = layui.func;
    var layer = layui.layer;


    /**
     * 管理
     */
    var Ddbxd = {
        tableId: "DdbxdTable"
    };

    Ddbxd.GetDateStr = function GetDateStr(days) {
        var dd = new Date();
        dd.setDate(dd.getDate()+days);//获取days天后的日期
        var y = dd.getFullYear();
        var m = dd.getMonth()+1;//获取当前月份的日期
        var d = dd.getDate();
        //判断 月
        if(m < 10){
            m = "0" + m;
        }else{
            m = m;
        }
        //判断 日n
        if(d < 10){//如果天数<10
            d = "0" + d;
        }else{
            d = d;
        }
        return y+"-"+m+"-"+d;
    }



    var zt=Ddbxd.GetDateStr(0);
    var predate = Ddbxd.GetDateStr(-3);
    date.render({
        elem: '#createTime',
        range: true,
        value: predate+' - '+zt,
        isInitValue: true
    });
    date.render({
        elem: '#finishTime',
        range: true,
        value: zt+' - '+zt,
        isInitValue: true
    });


    /**
     * 初始化表格的列
     */
    Ddbxd.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            {type: 'numbers',align:'center', title: '序号'},
            {field: 'originatorDeptName', sort: true, title: '店名',width:200},
            {field: 'title', sort: true, title: '标题',width:200},
            {field: 'baoxiaoren', sort: true, title: '报销人',width:200},
            {field: 'kj', sort: true, title: '会计',width:80},
            {field: 'zje', sort: true, title: '报销总金额',width:160},
            // {field: 'originator_userid', title: '发起人'},
            {field: 'status', sort: true, title: '状态',width:100,templet:function (data) {
                switch (data.status) {
                    case "NEW":return "刚申报";break;
                    case "RUNNING":return "审批中";break;
                    case "TERMINATED":return "被终止";break;
                    case "COMPLETED":return "已完成";break;
                }
                }},
            {field: 'result', sort: true, title: '审批结果',width:110,templet:function (data) {
                    switch (data.result) {
                        case "agree":return "同意";break;
                        case "refuse":return "拒绝";break;
                        default :return "";break;
                    }
                }},
            {field: 'createTime', sort: true,width:180, title: '发起时间'},
            {field: 'finishTime', sort: true,width:180, title: '完成时间'},
            {field:'sync',sort: true,title: "同步状态",width: 100,templet:function(data){
                    switch (data.sync) {
                        case "1":return "已同步";break;
                        default :return "";break;
                    }
                }},
            {align: 'center',  title: '操作',width:120,toolbar: '#tableBar',fixed: 'right'}

        ]];
    };

    $("#st").val("COMPLETED");
    form.render("select");

    var queryData = {};
    queryData['wcStartTime'] = zt;
    queryData['wcEndTime'] =zt;
    queryData['st'] =$("#st").val();

    var tabcof={
        elem: '#' + Ddbxd.tableId,
        url: Feng.ctxPath + '/ddbxd/list',
        method: 'post',
        page: false,
        where:queryData,
        height: "full-59",
        cellMinWidth: 100,
        cols: Ddbxd.initColumn(),
        done: function(res, curr, count){
            if(res.code!=0){
                Feng.error(res.message);
            }
        }
    };
    /**
     * 点击查询按钮
     */
    Ddbxd.search = function () {
        var queryData = {};
        var createTimeStr = $("#createTime").val();
        var finishTimeStr = $("#finishTime").val();
        if(createTimeStr!=""&&createTimeStr!=null){
            var time1 = createTimeStr.split(" - ");
            queryData['tjStartTime'] = time1[0];
            queryData['tjEndTime'] = time1[1];
        }else{
            queryData['tjStartTime'] = '';
            queryData['tjEndTime'] = '';
        }
        if(finishTimeStr!=""&&finishTimeStr!=null){
            var time1 = finishTimeStr.split(" - ");
            queryData['wcStartTime'] = time1[0];
            queryData['wcEndTime'] = time1[1];
        }else{
            queryData['wcStartTime'] = '';
            queryData['wcEndTime'] = '';
        }
        /*if(finishTimeStr==""||finishTimeStr==null){
            Feng.error("审批完成时间不能为空");
            return false;
        }*/
        queryData['kjName'] = $("#kj").val();
        queryData['shopName'] = $("#shopName").val();
        queryData['tijiaoren'] = $("#tijiaoren").val();
        queryData['baoxiaoren'] = $("#baoxiaoren").val();
        queryData['st'] = $("#st").val();
        tableResult.reload({where: queryData});
    };

   function initKj(){
       var ajax = new $ax(Feng.ctxPath + "btyBxd/getKj", function (data) {
           var ops="";
           for(var k of data){
               ops+='<option value="'+k.kj+'"+>'+k.kj+'</option> ';
           }
           $("#kj").append(ops);
           form.render('select');
       }, function (data) {
           Feng.error("同步失败!" + data.responseJSON.message + "!");
       });
       ajax.start();
   }
    initKj();
    /**
     * 导出excel按钮
     */
    Ddbxd.exportExcel = function () {
        var checkRows = table.checkStatus(Ddbxd.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Ddbxd.openEditDlg = function (data) {
        func.open({
            height: 520,
            title: '报销单详情',
            content: Feng.ctxPath + "/ddbxd/toDetail?id=" + data.id,
            tableId: Ddbxd.tableId
        });
    };

    //单个同步
    Ddbxd.btnsync = function (rowdata,row) {
        var ajax = new $ax(Feng.ctxPath + "/ddbxd/ddbxdSync/"+rowdata.id, function (data) {
            if (data.code == 1) {
                Feng.error(data.message);
            }else if(data.code == 200){
                Feng.success("同步成功！");
                Ddbxd.search();
            }
            /*if(data.data!=null){
                var ers= data.data.join("<br/>");
                layui.layer.open({
                    type: 1,
                    skin: 'layui-layer-rim', //样式类名
                    area: ['550px', '260px'], //宽高
                    shadeClose: true, //开启遮罩关闭
                    content: ers
                });
            }*/
        }, function (data) {
            Feng.error("同步失败!" + data.responseJSON.message + "!");
        });
        ajax.set("bxdid", rowdata.bxdid);
        ajax.start();
    };


    // 渲染表格
    var tableResult = table.render(tabcof);


    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Ddbxd.search();
    });

    //拉取数据
    $('#btnPull').click(function () {

        var tm = $("#createTime").val();
        if(tm==""){
            Feng.error("根据发起时间从钉钉拉取数据，请选择发起时间段！");
            return;
        }
        var timeArr = tm.split(" - ");
        var params={
            "tjStartTime": timeArr[0],
            "tjEndTime": timeArr[1]
        };
        var l_index;
        $.ajax({
            url: Feng.ctxPath + "/ddbxd/pullFromDingding",
            cache: false,
            dataType:"json",
            data: params,
            timeout: 600*1000,//10min
            beforeSend: function () {
                l_index = layer.load(1);
            },
            success: function (data) {
                if (data.code != 200) {
                    Feng.error(data.message);
                }else {
                    Feng.success("获取成功！");
                    Ddbxd.search();
                }
                layer.close(l_index);
            },
            error: function (data) {
                layer.alert('获取失败！');
                layer.close(l_index);
            }
        });
    });

    // 添加按钮点击事件
    $('#btnCopy').click(function () {
        var ajax = new $ax(Feng.ctxPath + "/ddbxd/copyBxd", function (data) {
            if (data.code == 1) {
                Feng.error(data.message);
                if(data.data!=null){
                    var ers= data.data.join("<br/>");
                    layui.layer.open({
                        type: 1,
                        skin: 'layui-layer-rim', //样式类名
                        area: ['550px', '260px'], //宽高
                        shadeClose: true, //开启遮罩关闭
                        content: ers
                    });
                }
                return;
            }
            Feng.success("同步成功！");
            if(data.data!=null){
                var ers= data.data.join("<br/>");
                layui.layer.open({
                    type: 1,
                    skin: 'layui-layer-rim', //样式类名
                    area: ['550px', '260px'], //宽高
                    shadeClose: true, //开启遮罩关闭
                    content: ers
                });
            }
            Ddbxd.search();
        }, function (data) {
            Feng.error("同步失败!" + data.responseJSON.message + "!");
        });
        // ajax.set("btyZxMdzxId", data.data[0].btyZxMdzxId);
        ajax.start();
    });

   /* Ddbxd.showLoad = function showLoad(){
        return layer.msg('努力中...',{icon: 16,shade: [0.5,'#f5f5f5'],scrollbar: false,offset: '0px',time:100000}) ;
    }
    Ddbxd.closeLoad = function closeLoad(index){
        layer.close(index);
    }*/

    //同步bxd
    $('#queryLastDaysData').click(function () {

        var tm = $("#finishTime").val();
        if(tm==""){
            Feng.error("根据审批完成时间生成报销单，请选择完成时间段！");
            return;
        }
        var timeArr = tm.split(" - ");
        var params={
            "wcStartTime": timeArr[0],
            "wcEndTime": timeArr[1]
        };
        var l_index;
        $.ajax({
            url: Feng.ctxPath + "/ddbxd/queryLastDaysData",
            cache: false,
            dataType:"json",
            data: params,
            beforeSend: function () {
                l_index = layer.load(1);
            },
            success: function (data) {
                if (data.code != 200) {
                    Feng.error(data.message);
                }else {
                    Feng.success("操作成功！");
                    Ddbxd.search();
                }
                layer.close(l_index);
            },
            error: function (data) {
                layer.alert('操作失败！');
                layer.close(l_index);
            }
        });

    });

    // 添根据完成时间同步
    $('#btnCopyFinish').click(function () {
        var ajax = new $ax(Feng.ctxPath + "/ddbxd/btnCopyFinish", function (data) {
            if (data.code == 1) {
                Feng.error(data.message);
                if(data.data!=null){
                    var ers= data.data.join("<br/>");
                    layui.layer.open({
                        type: 1,
                        skin: 'layui-layer-rim', //样式类名
                        area: ['550px', '260px'], //宽高
                        shadeClose: true, //开启遮罩关闭
                        content: ers
                    });
                }
                return;
            }
            Feng.success("同步成功！");
            if(data.data!=null){
                var ers= data.data.join("<br/>");
                layui.layer.open({
                    type: 1,
                    skin: 'layui-layer-rim', //样式类名
                    area: ['550px', '260px'], //宽高
                    shadeClose: true, //开启遮罩关闭
                    content: ers
                });
            }
            Ddbxd.search();
        }, function (data) {
            Feng.error("同步失败!" + data.responseJSON.message + "!");
        });
        // ajax.set("btyZxMdzxId", data.data[0].btyZxMdzxId);
        ajax.start();
    });



    // 导出excel
    $('#btnExp').click(function () {
        Ddbxd.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + Ddbxd.tableId + ')', function (obj) {
        var data = obj.data;
        var row=obj.tr[0];
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Ddbxd.openEditDlg(data);
        } else if (layEvent === 'sync') {
            Ddbxd.btnsync(data,row);
        }
    });


});
